package com.arron.prototype.deepclone;

import java.io.*;

public class DeepPrototype implements Serializable,Cloneable {

    public String name;//String 属性
    public DeepCloneableTarget deepCloneableTarget;//引用类型

    public DeepPrototype() {
        super();
    }

    /**
     * 深拷贝 -方式1 使用clone方法
     * @return
     * @throws CloneNotSupportedException
     */
    @Override
    public Object clone() throws CloneNotSupportedException {
        //这里完成对基本数据类型与String的克隆
        Object deep = super.clone();
        DeepPrototype deepPrototype =(DeepPrototype)deep;
        //对引用类型的属性，进行单独处理
        deepPrototype.deepCloneableTarget = (DeepCloneableTarget) deepCloneableTarget.clone();
        return deepPrototype;
    }

    public Object deepClone() {
        //创建流对象
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try {
            //序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepPrototype copyObj = (DeepPrototype) ois.readObject();
            return copyObj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {

            try {
                //关闭流
                ois.close();
                bis.close();
                oos.close();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
        }
    }
}
